<?php

/**
 * This is the model class for table "sd.order".
 *
 * The followings are the available columns in table 'sd.order':
 * @property string $id
 * @property string $user_id
 * @property string $name
 * @property string $region
 * @property string $city
 * @property string $address
 * @property string $comment
 * @property string $status
 * @property string $status_text
 * @property string $date
 * @property string $ip
 * @property string $phone
 * @property string $email
 *
 * The followings are the available model relations:
 * @property Users $user
 * @property OrderGoods[] $orderGoods
 */
class Order extends CBaseActiveRecord
{
	const STATUS_NEW = 'new';
	const STATUS_DRAFT = 'draft';
	const STATUS_DISCLAIMER = 'disclaimer';
	const STATUS_PROCESSED = 'processed';
	const STATUS_PROCESSING = 'processing';
	const STATUS_NOT_AVAILABLE = 'not_available';
	const STATUS_DELETED = 'deleted';

	public $statuses = array(
		self::STATUS_NEW => 'Новий',
		self::STATUS_DRAFT => 'Не завершонный пользователем',
		self::STATUS_DISCLAIMER => 'Отказ',
		self::STATUS_PROCESSED => 'Обработан',
		self::STATUS_PROCESSING => 'В обработке',
		self::STATUS_NOT_AVAILABLE => 'Нет в наличии',
		self::STATUS_DELETED => 'Удален',
	);

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'sd.order';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('date', 'required'),
			array('user_id', 'length', 'max'=>10),
			array('name, address, comment, status_text', 'length', 'max'=>255),
			array('region, city', 'length', 'max'=>45),
			array('status', 'length', 'max'=>12),
			array('ip', 'length', 'max'=>15),
			array('phone', 'length', 'max'=>20),
			array('email', 'length', 'max'=>150),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, user_id, name, region, city, address, comment, status, status_text, date, ip, phone, email', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'user' => array(self::BELONGS_TO, 'Users', 'user_id'),
			'orderGoods' => array(self::HAS_MANY, 'OrderGoods', 'order_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'user_id' => 'User',
			'name' => 'Name',
			'region' => 'Region',
			'city' => 'City',
			'address' => 'Address',
			'comment' => 'Comment',
			'status' => 'Status',
			'status_text' => 'Status Text',
			'date' => 'Date',
			'ip' => 'Ip',
			'phone' => 'Phone',
			'email' => 'Email',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('user_id',$this->user_id,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('region',$this->region,true);
		$criteria->compare('city',$this->city,true);
		$criteria->compare('address',$this->address,true);
		$criteria->compare('comment',$this->comment,true);
		$criteria->compare('status',$this->status,true);
		$criteria->compare('status_text',$this->status_text,true);
		$criteria->compare('date',$this->date,true);
		$criteria->compare('ip',$this->ip,true);
		$criteria->compare('phone',$this->phone,true);
		$criteria->compare('email',$this->email,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Order the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function _addGoodsToCart($goodsId, $quantity, $params = array())
	{
		$session=new CHttpSession;
		$session->open();

		$cart = array();
		if(!empty($session['cart']))
			$cart = $session['cart'];


		if(empty($cart['goods']))
			$cart['goods'] = array();

		if($quantity)
		{
			$cart['goods'][$goodsId]['quantity'] = $quantity;
			$cart['goods'][$goodsId]['params'] = $params;
		}
		else
			unset($cart['goods'][$goodsId]);

//		print_r($cart); exit;

		$session['cart'] = $cart;

		return true;
	}

	public function addGoodsToCart($goodsId, $quantity, $params = array(), $doAdd = true)
	{
		$session=new CHttpSession;
		$session->open();

		$cart = array();
		if(!empty($session['cart']))
			$cart = $session['cart'];

		$oOrder = null;
		if(!empty($cart['orderId']))
		{
			$oOrder = $this->findByPk($cart['orderId']);
		}
		else
		{
			$oOrder = new Order();
			$oOrder->date = date('Y-m-d H:i:s');
			$oOrder->ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';

			if(!$oOrder->save())
				return false;

			$cart['orderId'] = $oOrder->getPrimaryKey();
			$oOrder->id = $cart['orderId'];
		}

		$oOrderGoods = new OrderGoods();
		if($quantity > 0)
		{
			$oOrderGoods = $oOrderGoods->findByAttributes(array(
			                                    'order_id' => $oOrder->id,
			                                    'goods_id' => $goodsId
			                               ));

			if($oOrderGoods)
			{
				if($doAdd)
					$oOrderGoods->quantity += $quantity;
				else
					$oOrderGoods->quantity = $quantity;

				$oOrderGoods->save();
			}
			else
			{
				$oOrderGoods = new OrderGoods();

				$oOrderGoods->order_id = $oOrder->id;
				$oOrderGoods->goods_id = $goodsId;
				$oOrderGoods->quantity = $quantity;
				$oOrderGoods->properties = serialize((array)$params);

				$oOrderGoods->save();
			}
		}
		else
		{
			$oOrderGoods->deleteAllByAttributes(array(
			                                         'order_id' => $oOrder->id,
			                                         'goods_id' => $goodsId
			                                    ));
		}


		$session['cart'] = $cart;

		return true;
	}

	public function getCountInCart($goodsId = null)
	{
		$orderId = $this->getOrderId();
		if(!$orderId)
			return 0;

		$oOrderGoods = new OrderGoods();
		if($goodsId)
		{
			$oOrderGoods = $oOrderGoods->findByAttributes(array(
			                                                   'order_id' => $orderId,
			                                                   'goods_id' => $goodsId
			                                              ));

			if($oOrderGoods)
				return $oOrderGoods->quantity;
		}
		else
		{
			$row = $oOrderGoods->findBySql('SELECT sum(quantity) as quantity FROM order_goods WHERE order_id='. $orderId);
			if($row)
				return $row->quantity;
		}

		return 0;
	}

	public function getInCart()
	{
		$orderId = $this->getOrderId();
		if(!$orderId)
			return array();

		$oOrderGoods = new OrderGoods();
		$oOrderGoods = $oOrderGoods->findAllByAttributes(array('order_id' => $orderId));


		return $oOrderGoods;

//		$aIds = array();
//		foreach($oOrderGoods as $oOrderRow)
//		{
//			$aIds[$oOrderRow->goods_id] = $oOrderRow->goods_id;
//		}
//
//		return $aIds;
	}

	public function getOrderId()
	{
		$session=new CHttpSession;
		$session->open();

		if(empty($session['cart']) || empty($session['cart']['orderId']))
			return 0;

		return $session['cart']['orderId'];

	}

	public function getAll($oPager = null, $status = null)
	{
		$oCriteria = $this->getDbCriteria();

		$oCriteria->order = 'id ASC';

		if($status)
			$oCriteria->addInCondition('status', (array)$status);

		if($oPager)
		{
			$oPager->setItemCount($this->count($oCriteria));
			$oPager->applyLimit($oCriteria);
		}

		return $this->findAll($oCriteria);
	}

}
